/**
 * 标签管理模块JavaScript
 * 基于Apple Design System的CRM标签管理交互逻辑
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let currentTagId = null;
let currentView = 'table';
let tags = [];
let filteredTags = [];
let currentPage = 1;
let pageSize = 20;
let sortField = 'name';
let sortDirection = 'asc';

// 模拟标签数据
const mockTags = [
    {
        id: 1,
        name: 'VIP客户',
        category: '客户等级',
        description: '高价值客户，享受优先服务',
        color: '#FFD700',
        usageCount: 324,
        status: 'active',
        createdAt: '2025-01-10'
    },
    {
        id: 2,
        name: '身体健康',
        category: '健康状况',
        description: '身体状况良好，无特殊护理需求',
        color: '#34C759',
        usageCount: 856,
        status: 'active',
        createdAt: '2025-01-08'
    },
    {
        id: 3,
        name: '自然风光',
        category: '兴趣偏好',
        description: '喜欢山水风景、自然景观',
        color: '#32CD32',
        usageCount: 542,
        status: 'active',
        createdAt: '2025-01-05'
    },
    {
        id: 4,
        name: '需要照顾',
        category: '健康状况',
        description: '需要额外照顾和帮助的客户',
        color: '#FF3B30',
        usageCount: 127,
        status: 'active',
        createdAt: '2025-01-03'
    },
    {
        id: 5,
        name: '优质客户',
        category: '客户等级',
        description: '服务质量好，忠诚度高',
        color: '#007AFF',
        usageCount: 456,
        status: 'active',
        createdAt: '2025-01-02'
    },
    {
        id: 6,
        name: '人文历史',
        category: '兴趣偏好',
        description: '对历史文化感兴趣',
        color: '#8B4513',
        usageCount: 289,
        status: 'active',
        createdAt: '2024-12-28'
    },
    {
        id: 7,
        name: '高端服务',
        category: '服务需求',
        description: '需要高品质的服务体验',
        color: '#800080',
        usageCount: 198,
        status: 'active',
        createdAt: '2024-12-25'
    },
    {
        id: 8,
        name: '团体出行',
        category: '服务需求',
        description: '喜欢与朋友家人一起旅行',
        color: '#20B2AA',
        usageCount: 367,
        status: 'active',
        createdAt: '2024-12-22'
    }
];

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeTagManagement();
});

// 初始化标签管理
function initializeTagManagement() {
    // 初始化数据
    tags = [...mockTags];
    filteredTags = [...tags];
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 渲染页面
    renderTags();
    updateStatistics();
    
    console.log('标签管理系统初始化完成');
}

// 绑定事件监听器
function bindEventListeners() {
    // 搜索功能
    const searchInput = document.getElementById('search-input');
    const searchClear = document.getElementById('search-clear');
    
    if (searchInput) {
        searchInput.addEventListener('input', handleSearch);
    }
    
    if (searchClear) {
        searchClear.addEventListener('click', clearSearch);
    }
    
    // 筛选功能
    const categoryFilter = document.getElementById('category-filter');
    const statusFilter = document.getElementById('status-filter');
    const resetFilters = document.getElementById('reset-filters');
    
    if (categoryFilter) {
        categoryFilter.addEventListener('change', handleFilter);
    }
    
    if (statusFilter) {
        statusFilter.addEventListener('change', handleFilter);
    }
    
    if (resetFilters) {
        resetFilters.addEventListener('click', resetAllFilters);
    }
    
    // 新增标签按钮
    const addTagBtn = document.getElementById('add-tag-btn');
    if (addTagBtn) {
        addTagBtn.addEventListener('click', showAddTagModal);
    }
    
    // 导入导出按钮
    const importTagsBtn = document.getElementById('import-tags-btn');
    const exportTagsBtn = document.getElementById('export-tags-btn');
    
    if (importTagsBtn) {
        importTagsBtn.addEventListener('click', importTags);
    }
    
    if (exportTagsBtn) {
        exportTagsBtn.addEventListener('click', exportTags);
    }
    
    // 视图切换
    const viewBtns = document.querySelectorAll('.view-btn');
    viewBtns.forEach(btn => {
        btn.addEventListener('click', switchView);
    });
    
    // 排序功能
    const sortableThs = document.querySelectorAll('.sortable');
    sortableThs.forEach(th => {
        th.addEventListener('click', handleSort);
    });
    
    // 分页
    const pageSize = document.getElementById('page-size');
    if (pageSize) {
        pageSize.addEventListener('change', handlePageSizeChange);
    }
    
    // 模态框事件
    setupModalEvents();
    
    // 颜色选择器事件
    setupColorPickerEvents();
    
    // 分类卡片点击
    const categoryCards = document.querySelectorAll('.category-card');
    categoryCards.forEach(card => {
        card.addEventListener('click', handleCategoryClick);
    });
}

// 搜索处理
function handleSearch(event) {
    const searchTerm = event.target.value.toLowerCase().trim();
    
    if (searchTerm === '') {
        filteredTags = [...tags];
    } else {
        filteredTags = tags.filter(tag => 
            tag.name.toLowerCase().includes(searchTerm) ||
            tag.description.toLowerCase().includes(searchTerm) ||
            tag.category.toLowerCase().includes(searchTerm)
        );
    }
    
    currentPage = 1;
    renderTags();
    updatePagination();
}

// 清除搜索
function clearSearch() {
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.value = '';
        filteredTags = [...tags];
        currentPage = 1;
        renderTags();
        updatePagination();
    }
}

// 筛选处理
function handleFilter() {
    const categoryFilter = document.getElementById('category-filter');
    const statusFilter = document.getElementById('status-filter');
    
    const selectedCategory = categoryFilter?.value || '';
    const selectedStatus = statusFilter?.value || '';
    
    filteredTags = tags.filter(tag => {
        const categoryMatch = !selectedCategory || tag.category === selectedCategory;
        const statusMatch = !selectedStatus || tag.status === selectedStatus;
        return categoryMatch && statusMatch;
    });
    
    currentPage = 1;
    renderTags();
    updatePagination();
}

// 重置所有筛选器
function resetAllFilters() {
    // 重置搜索
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.value = '';
    }
    
    // 重置筛选器
    const categoryFilter = document.getElementById('category-filter');
    const statusFilter = document.getElementById('status-filter');
    
    if (categoryFilter) {
        categoryFilter.value = '';
    }
    
    if (statusFilter) {
        statusFilter.value = '';
    }
    
    // 重置数据
    filteredTags = [...tags];
    currentPage = 1;
    renderTags();
    updatePagination();
}

// 排序处理
function handleSort(event) {
    const field = event.target.closest('th').dataset.sort;
    
    if (sortField === field) {
        sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
        sortField = field;
        sortDirection = 'asc';
    }
    
    // 更新排序图标
    updateSortIcons();
    
    // 执行排序
    sortTags();
    renderTags();
}

// 更新排序图标
function updateSortIcons() {
    const sortableThs = document.querySelectorAll('.sortable');
    sortableThs.forEach(th => {
        const icon = th.querySelector('i');
        const field = th.dataset.sort;
        
        if (field === sortField) {
            icon.className = sortDirection === 'asc' ? 'fas fa-sort-up' : 'fas fa-sort-down';
        } else {
            icon.className = 'fas fa-sort';
        }
    });
}

// 排序标签
function sortTags() {
    filteredTags.sort((a, b) => {
        let aVal = a[sortField];
        let bVal = b[sortField];
        
        // 特殊处理数字字段
        if (sortField === 'usageCount') {
            aVal = parseInt(aVal);
            bVal = parseInt(bVal);
        }
        
        // 特殊处理日期字段
        if (sortField === 'createdAt') {
            aVal = new Date(aVal);
            bVal = new Date(bVal);
        }
        
        if (sortDirection === 'asc') {
            return aVal > bVal ? 1 : -1;
        } else {
            return aVal < bVal ? 1 : -1;
        }
    });
}

// 视图切换
function switchView(event) {
    const viewType = event.target.closest('.view-btn').dataset.view;
    currentView = viewType;
    
    // 更新按钮状态
    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.closest('.view-btn').classList.add('active');
    
    // 切换视图
    const tableView = document.getElementById('table-view');
    const gridView = document.getElementById('grid-view');
    
    if (viewType === 'table') {
        tableView.style.display = 'block';
        gridView.style.display = 'none';
    } else {
        tableView.style.display = 'none';
        gridView.style.display = 'block';
    }
    
    renderTags();
}

// 渲染标签列表
function renderTags() {
    if (currentView === 'table') {
        renderTableView();
    } else {
        renderGridView();
    }
    
    updatePagination();
}

// 渲染表格视图
function renderTableView() {
    const tbody = document.getElementById('tags-table-body');
    if (!tbody) return;
    
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = filteredTags.slice(startIndex, endIndex);
    
    tbody.innerHTML = pageData.map(tag => `
        <tr class="tag-row" data-tag-id="${tag.id}">
            <td class="tag-name">
                <div class="tag-display">
                    <span class="tag" style="background-color: ${tag.color}; color: ${getContrastColor(tag.color)}">${tag.name}</span>
                    <span class="tag-text">${tag.name}</span>
                </div>
            </td>
            <td>
                <span class="category-badge category-${getCategoryClass(tag.category)}">${tag.category}</span>
            </td>
            <td class="tag-description" title="${tag.description}">${tag.description}</td>
            <td class="usage-count">${tag.usageCount}</td>
            <td>
                <span class="status-badge status-${tag.status}">
                    ${tag.status === 'active' ? '启用中' : '已停用'}
                </span>
            </td>
            <td>${tag.createdAt}</td>
            <td class="actions">
                <div class="action-buttons">
                    <button class="action-btn" title="编辑" onclick="editTag(${tag.id})">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="action-btn" title="查看客户" onclick="viewTagCustomers(${tag.id})">
                        <i class="fas fa-users"></i>
                    </button>
                    <button class="action-btn" title="更多操作" onclick="showTagActions(${tag.id})">
                        <i class="fas fa-ellipsis-h"></i>
                    </button>
                </div>
            </td>
        </tr>
    `).join('');
}

// 渲染卡片视图
function renderGridView() {
    const container = document.getElementById('tags-grid-body');
    if (!container) return;
    
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = filteredTags.slice(startIndex, endIndex);
    
    container.innerHTML = pageData.map(tag => `
        <div class="tag-card" data-tag-id="${tag.id}">
            <div class="tag-card-header">
                <span class="tag large" style="background-color: ${tag.color}; color: ${getContrastColor(tag.color)}">${tag.name}</span>
                <div class="tag-actions">
                    <button class="tag-action-btn" title="编辑" onclick="editTag(${tag.id})">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="tag-action-btn" title="更多" onclick="showTagActions(${tag.id})">
                        <i class="fas fa-ellipsis-h"></i>
                    </button>
                </div>
            </div>
            
            <div class="tag-card-body">
                <div class="tag-category">
                    <span class="category-badge category-${getCategoryClass(tag.category)}">${tag.category}</span>
                </div>
                <p class="tag-description">${tag.description}</p>
                
                <div class="tag-stats">
                    <div class="stat-item">
                        <i class="fas fa-users"></i>
                        <span>${tag.usageCount}名客户使用</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-calendar"></i>
                        <span>${tag.createdAt} 创建</span>
                    </div>
                </div>
            </div>
            
            <div class="tag-card-footer">
                <button class="card-btn primary" onclick="viewTagCustomers(${tag.id})">
                    <i class="fas fa-users"></i>
                    查看客户
                </button>
                <span class="status-badge status-${tag.status}">
                    ${tag.status === 'active' ? '启用中' : '已停用'}
                </span>
            </div>
        </div>
    `).join('');
}

// 获取分类样式类
function getCategoryClass(category) {
    const categoryMap = {
        '客户等级': 'level',
        '健康状况': 'health',
        '兴趣偏好': 'interest',
        '服务需求': 'service'
    };
    return categoryMap[category] || 'other';
}

// 获取对比色
function getContrastColor(hexColor) {
    // 移除#号
    const hex = hexColor.replace('#', '');
    
    // 转换为RGB
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    
    // 计算亮度
    const brightness = (r * 299 + g * 587 + b * 114) / 1000;
    
    // 返回对比色
    return brightness > 128 ? '#000000' : '#FFFFFF';
}

// 更新统计数据
function updateStatistics() {
    const totalTags = tags.length;
    const activeTags = tags.filter(tag => tag.status === 'active').length;
    const categories = [...new Set(tags.map(tag => tag.category))].length;
    const totalUsage = tags.reduce((sum, tag) => sum + tag.usageCount, 0);
    
    // 更新统计卡片
    const statCards = document.querySelectorAll('.stat-card');
    if (statCards.length >= 4) {
        statCards[0].querySelector('.stat-number').textContent = totalTags;
        statCards[1].querySelector('.stat-number').textContent = activeTags;
        statCards[2].querySelector('.stat-number').textContent = categories;
        statCards[3].querySelector('.stat-number').textContent = totalUsage.toLocaleString();
    }
    
    // 更新结果计数
    const resultCount = document.querySelector('.result-count');
    if (resultCount) {
        resultCount.textContent = `共 ${filteredTags.length} 个标签`;
    }
}

// 更新分页
function updatePagination() {
    const totalPages = Math.ceil(filteredTags.length / pageSize);
    const paginationInfo = document.querySelector('.pagination-info');
    const pagination = document.querySelector('.pagination');
    
    if (paginationInfo) {
        const start = (currentPage - 1) * pageSize + 1;
        const end = Math.min(currentPage * pageSize, filteredTags.length);
        paginationInfo.textContent = `显示第 ${start}-${end} 条，共 ${filteredTags.length} 条记录`;
    }
    
    if (pagination) {
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <button class="page-btn" ${currentPage === 1 ? 'disabled' : ''} onclick="goToPage(${currentPage - 1})">
                <i class="fas fa-chevron-left"></i>
            </button>
        `;
        
        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                paginationHTML += `
                    <button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">
                        ${i}
                    </button>
                `;
            } else if (i === currentPage - 2 || i === currentPage + 2) {
                paginationHTML += '<span class="page-dots">...</span>';
            }
        }
        
        // 下一页按钮
        paginationHTML += `
            <button class="page-btn" ${currentPage === totalPages ? 'disabled' : ''} onclick="goToPage(${currentPage + 1})">
                <i class="fas fa-chevron-right"></i>
            </button>
        `;
        
        pagination.innerHTML = paginationHTML;
    }
}

// 跳转到指定页面
function goToPage(page) {
    const totalPages = Math.ceil(filteredTags.length / pageSize);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        renderTags();
    }
}

// 处理页面大小变化
function handlePageSizeChange(event) {
    pageSize = parseInt(event.target.value);
    currentPage = 1;
    renderTags();
}

// 显示新增标签模态框
function showAddTagModal() {
    currentTagId = null;
    const modal = document.getElementById('tag-modal');
    const title = document.getElementById('tag-modal-title');
    const form = document.getElementById('tag-form');
    
    if (title) {
        title.textContent = '新增标签';
    }
    
    if (form) {
        form.reset();
        // 设置默认颜色
        const colorInput = document.getElementById('tag-color');
        if (colorInput) {
            colorInput.value = '#007AFF';
        }
    }
    
    if (modal) {
        modal.classList.add('show');
    }
}

// 编辑标签
function editTag(tagId) {
    const tag = tags.find(t => t.id === tagId);
    if (!tag) return;
    
    currentTagId = tagId;
    const modal = document.getElementById('tag-modal');
    const title = document.getElementById('tag-modal-title');
    
    if (title) {
        title.textContent = '编辑标签';
    }
    
    // 填充表单数据
    const nameInput = document.getElementById('tag-name');
    const categorySelect = document.getElementById('tag-category');
    const descriptionTextarea = document.getElementById('tag-description');
    const colorInput = document.getElementById('tag-color');
    const statusRadios = document.querySelectorAll('input[name="tag-status"]');
    
    if (nameInput) nameInput.value = tag.name;
    if (categorySelect) categorySelect.value = tag.category;
    if (descriptionTextarea) descriptionTextarea.value = tag.description;
    if (colorInput) colorInput.value = tag.color;
    
    statusRadios.forEach(radio => {
        radio.checked = radio.value === tag.status;
    });
    
    if (modal) {
        modal.classList.add('show');
    }
}

// 保存标签
function saveTag() {
    const nameInput = document.getElementById('tag-name');
    const categorySelect = document.getElementById('tag-category');
    const descriptionTextarea = document.getElementById('tag-description');
    const colorInput = document.getElementById('tag-color');
    const statusRadio = document.querySelector('input[name="tag-status"]:checked');
    
    // 验证必填字段
    if (!nameInput?.value.trim() || !categorySelect?.value) {
        alert('请填写必填字段');
        return;
    }
    
    const tagData = {
        name: nameInput.value.trim(),
        category: categorySelect.value,
        description: descriptionTextarea?.value.trim() || '',
        color: colorInput?.value || '#007AFF',
        status: statusRadio?.value || 'active'
    };
    
    if (currentTagId) {
        // 编辑现有标签
        const tagIndex = tags.findIndex(t => t.id === currentTagId);
        if (tagIndex !== -1) {
            tags[tagIndex] = { ...tags[tagIndex], ...tagData };
        }
    } else {
        // 新增标签
        const newTag = {
            id: Date.now(),
            ...tagData,
            usageCount: 0,
            createdAt: new Date().toISOString().split('T')[0]
        };
        tags.push(newTag);
    }
    
    // 更新显示
    filteredTags = [...tags];
    renderTags();
    updateStatistics();
    closeTagModal();
    
    console.log(currentTagId ? '标签更新成功' : '标签创建成功');
}

// 关闭标签模态框
function closeTagModal() {
    const modal = document.getElementById('tag-modal');
    if (modal) {
        modal.classList.remove('show');
    }
    currentTagId = null;
}

// 显示标签操作菜单
function showTagActions(tagId) {
    currentTagId = tagId;
    const modal = document.getElementById('tag-action-modal');
    if (modal) {
        modal.classList.add('show');
    }
}

// 关闭标签操作模态框
function closeTagActionModal() {
    const modal = document.getElementById('tag-action-modal');
    if (modal) {
        modal.classList.remove('show');
    }
    currentTagId = null;
}

// 复制标签
function duplicateTag() {
    if (!currentTagId) return;
    
    const tag = tags.find(t => t.id === currentTagId);
    if (!tag) return;
    
    const newTag = {
        ...tag,
        id: Date.now(),
        name: tag.name + ' (副本)',
        usageCount: 0,
        createdAt: new Date().toISOString().split('T')[0]
    };
    
    tags.push(newTag);
    filteredTags = [...tags];
    renderTags();
    updateStatistics();
    closeTagActionModal();
    
    console.log('标签复制成功');
}

// 查看使用该标签的客户
function viewTagCustomers(tagId) {
    const tag = tags.find(t => t.id === tagId);
    if (!tag) return;
    
    console.log(`查看使用标签"${tag.name}"的客户列表`);
    alert(`查看使用标签"${tag.name}"的 ${tag.usageCount} 名客户\n\n此功能将跳转到客户管理页面并应用标签筛选。`);
    
    closeTagActionModal();
}

// 导出标签数据
function exportTagData() {
    if (!currentTagId) return;
    
    const tag = tags.find(t => t.id === currentTagId);
    if (!tag) return;
    
    console.log(`导出标签"${tag.name}"的相关数据`);
    alert(`导出标签"${tag.name}"的数据\n\n包括标签信息和使用该标签的客户数据。`);
    
    closeTagActionModal();
}

// 删除标签
function deleteTag() {
    if (!currentTagId) return;
    
    const tag = tags.find(t => t.id === currentTagId);
    if (!tag) return;
    
    if (tag.usageCount > 0) {
        const confirmed = confirm(`标签"${tag.name}"正在被 ${tag.usageCount} 名客户使用。\n\n删除后这些客户将失去此标签，是否继续？`);
        if (!confirmed) return;
    } else {
        const confirmed = confirm(`确定要删除标签"${tag.name}"吗？`);
        if (!confirmed) return;
    }
    
    // 删除标签
    const tagIndex = tags.findIndex(t => t.id === currentTagId);
    if (tagIndex !== -1) {
        tags.splice(tagIndex, 1);
        filteredTags = [...tags];
        renderTags();
        updateStatistics();
        closeTagActionModal();
        
        console.log('标签删除成功');
    }
}

// 导入标签
function importTags() {
    console.log('导入标签功能');
    alert('导入标签功能\n\n支持从Excel或CSV文件导入标签数据。');
}

// 导出标签
function exportTags() {
    console.log('导出标签功能');
    alert('导出标签功能\n\n将当前标签列表导出为Excel或CSV文件。');
}

// 分类卡片点击处理
function handleCategoryClick(event) {
    const category = event.currentTarget.dataset.category;
    const categoryFilter = document.getElementById('category-filter');
    
    if (categoryFilter) {
        categoryFilter.value = category;
        handleFilter();
    }
}

// 设置模态框事件
function setupModalEvents() {
    // 点击遮罩层关闭模态框
    document.addEventListener('click', function(event) {
        if (event.target.classList.contains('modal-overlay')) {
            const modals = document.querySelectorAll('.modal-overlay.show');
            modals.forEach(modal => {
                modal.classList.remove('show');
            });
            currentTagId = null;
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            const modals = document.querySelectorAll('.modal-overlay.show');
            modals.forEach(modal => {
                modal.classList.remove('show');
            });
            currentTagId = null;
        }
    });
}

// 设置颜色选择器事件
function setupColorPickerEvents() {
    const colorInput = document.getElementById('tag-color');
    const colorPresets = document.querySelectorAll('.color-preset');
    
    // 预设颜色点击
    colorPresets.forEach(preset => {
        preset.addEventListener('click', function(event) {
            event.preventDefault();
            const color = this.dataset.color;
            if (colorInput) {
                colorInput.value = color;
            }
            
            // 更新选中状态
            colorPresets.forEach(p => p.classList.remove('active'));
            this.classList.add('active');
        });
    });
    
    // 颜色输入变化
    if (colorInput) {
        colorInput.addEventListener('change', function() {
            // 移除所有预设颜色的选中状态
            colorPresets.forEach(p => p.classList.remove('active'));
            
            // 如果选择的是预设颜色，则选中对应的预设
            const selectedColor = this.value.toUpperCase();
            colorPresets.forEach(preset => {
                if (preset.dataset.color.toUpperCase() === selectedColor) {
                    preset.classList.add('active');
                }
            });
        });
    }
}

// 工具函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 响应式处理
function handleResize() {
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');
    
    if (window.innerWidth <= 1024) {
        // 移动端处理
        if (sidebar) {
            sidebar.classList.add('mobile');
        }
        if (mainContent) {
            mainContent.classList.add('mobile');
        }
    } else {
        // 桌面端处理
        if (sidebar) {
            sidebar.classList.remove('mobile');
        }
        if (mainContent) {
            mainContent.classList.remove('mobile');
        }
    }
}

// 监听窗口大小变化
window.addEventListener('resize', debounce(handleResize, 250));

// 初始调用响应式处理
handleResize();